package com.thinkit.cms.service.resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.thinkit.cms.api.resource.SysFileGroupService;
import com.thinkit.cms.api.resource.SysResourceService;
import com.thinkit.cms.api.site.SiteService;
import com.thinkit.cms.dto.resource.SysResourceDto;
import com.thinkit.cms.entity.resource.SysResource;
import com.thinkit.cms.mapper.resource.SysResourceMapper;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.core.constant.Constants;
import com.thinkit.nosql.annotation.CacheClear;
import com.thinkit.utils.model.PageDto;
import com.thinkit.utils.properties.ThinkItProperties;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LG
 * @since 2019-11-11
 */
@Service
public class SysResourceServiceImpl extends BaseServiceImpl<SysResourceDto, SysResource, SysResourceMapper> implements SysResourceService {


    @Autowired
    SysFileGroupService sysFileGroupService;

    @Autowired
    ThinkItProperties thinkItProperties;

    @Autowired
    SiteService siteService;

    @Cacheable(value = Constants.cacheName, key = "#root.targetClass+'.'+#root.methodName+'.'+#p0", unless = "#result == null")
    @Override
    public String getfilePathById(String id) {
        String path = "";
        if (Checker.BeNotBlank(id)) {
            QueryWrapper<SysResource> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id).select("file_full_path");
            SysResource sysResource = super.baseMapper.selectOne(queryWrapper);
            if (Checker.BeNotNull(sysResource)) {
                path = sysResource.getFileFullPath();
            }
        }
        return path;
    }

    @CacheClear(keys = {"getfilePathById", "getByPks", "getByPk"})
    @Override
    public void deleteByFilePath(String filePath) {
        Map<String, Object> param = new HashMap<>(16);
        param.put("file_path", filePath);
        baseMapper.deleteByMap(param);
    }

    @Override
    public PageDto<SysResourceDto> listGroupPage(PageDto<SysResourceDto> pageDto) {
        List<String> gids= sysFileGroupService.listGroupIds();
        IPage<SysResourceDto> pages = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        IPage<SysResourceDto> result = baseMapper.listGroupPage(pages, pageDto.getDto(),gids,null);
        PageDto<SysResourceDto> resultSearch = new PageDto(result.getTotal(), result.getPages(), result.getCurrent(), Checker.BeNotEmpty(result.getRecords()) ? result.getRecords() : Lists.newArrayList());
        return resultSearch;
    }

    @Override
    public void downFile(String id, HttpServletResponse response) {
        String fileUrl = baseMapper.getFileUrl(id,null);
        if(Checker.BeNotBlank(fileUrl)){
            String domain = siteService.getDomain(null,getSiteId());
            fileUrl=thinkItProperties.getFileLocalUrl(fileUrl,domain);
            try {
                down(fileUrl,response);
            } catch (IOException e) {
                response.setHeader("FileName", "下载失败.txt");
                log.error("下载文件失败!"+e.getMessage());
                e.printStackTrace();
            }
        }

    }

    private File down(String filePath, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if(file.exists()){
            InputStream in = null;
            OutputStream out = null;
            response.setCharacterEncoding(Constants.DEFAULT_CHARSET_NAME);
            response.setHeader("content-disposition","attachment;fileName="+file.getName());
            response.setHeader("FileName", file.getName());
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            try {
                out=  response.getOutputStream();
                in = new FileInputStream(file);
                byte[] buffer  = new byte[1024];
                int i=in.read(buffer );
                while (i!=-1){
                    out.write(buffer , 0, i);//将缓冲区的数据输出到浏览器
                    i= in.read(buffer );
                }
            } catch (IOException e) {
                throw e;
            }finally {
                in.close();
                out.close();
            }
        }
        return file;
    }
}
